import re
import json
from playwright.sync_api import Playwright, sync_playwright
import os
import requests
from requests import RequestException
import datetime


class TodayStudentData:
    def __init__(self):
        self.session = requests.Session()
        # self.base_url = 'http://127.0.0.1:8081'
        self.base_url = 'http://101.200.166.120:8081'

    # 获取当天学员及导师分配情况
    def getTodayStudentData(self):
        url = '/autoMsg/getTodayStudentAndTeacher'
        print(self.base_url + url)
        result = self.session.request('GET', url=f"{self.base_url}{url}", json=None)
        print(result.text)
        if result.status_code == 200 and result.json().get('code') == 200:
            return result.json()['data']
        else:
            raise RequestException('获取当天学员及导师分配情况接口请求失败')

    # 拉群结果回调
    def sendMsg(self, sendData):
        url = '/autoMsg/studentAndTeacherCallBack'
        print(self.base_url + url)
        result = self.session.request('POST', url=f"{self.base_url}{url}", json=sendData)
        print(result.text)
        if result.status_code == 200 and result.json().get('code') == 200:
            return result.json()['data']
        else:
            raise RequestException('拉群结果回调接口请求失败')


class OpenFeishuMessage:
    def __init__(self, playwright: Playwright, headless: bool = False):
        self.playwright = playwright
        self.headless = headless
        self.browner = self.playwright.chromium.launch(channel='msedge', headless=headless)
        self.context = self.browner.new_context()
        self.page = self.context.new_page()
        self.title = self.page.title()
        self.lark_suite_url = 'https://www.feishu.cn/messenger/'
        self.cookies_file_path = 'cookies.json'

    def open_browser(self):

        # 加载本地cookie
        if os.path.exists(self.cookies_file_path):
            with open(self.cookies_file_path, "r") as f:
                settings = json.load(f)
                self.context.add_cookies(settings)

        self.page.goto(self.lark_suite_url)
        loginLocator = self.page.locator('.new-scan-login-box')

        # 记载页面并保存cookies
        if loginLocator.count() > 0:
            while True:
                self.page.wait_for_timeout(1000 * 2)
                print('等待登录')
                if self.page.locator('.new-scan-login-box').count() == 0:
                    print('用户登录成功！！!')
                    self.save_cookies()
                    break
        print('登陆成功，重新进入页面')
        self.page.goto(self.lark_suite_url)

    # 创建群组
    def buildGroup(self, student, teacher):
        page = self.page
        page.locator(".lark-drag-disable > .larkc-svg-icon").click()
        page.locator("div").filter(has_text=re.compile(r"^创建群组$")).click()
        self.page.wait_for_timeout(1000 * 2)

        # 设置群名
        student_name = student.get('name')
        current_date = datetime.date.today()
        formatted_date = current_date.strftime('%y%m%d')
        groupName = '%s专属支持群(%s)' % (student_name, formatted_date)
        page.get_by_placeholder("输入群名称（选填）").fill(groupName)

        # 拉人
        page.get_by_placeholder("搜索").click()
        width = page.viewport_size['width']
        height = page.viewport_size['height']

        # 学生
        page.get_by_placeholder("搜索").fill(student_name)
        self.page.wait_for_timeout(1000 * 1)
        student_avatar_key = re.search(r"/v2_[^~]+", student.get('avatar_url')).group(0)
        for locator in page.locator('.list_items').locator('.larkc-avatar-img').all():
            if student_avatar_key in locator.get_attribute('src'):
                print('学生匹配成功')
                locator.click()
                break
        # 老师
        page.get_by_placeholder("搜索").click()
        page.get_by_placeholder("搜索").clear()
        teacher_name = teacher.get('name')
        page.get_by_placeholder("搜索").fill(teacher_name)
        self.page.wait_for_timeout(1000 * 1)
        teacher_avatar_key = re.search(r"/v2_[^~]+", teacher.get('avatar_url')).group(0)
        for locator in page.locator('.list_items').locator('.larkc-avatar-img').all():
            if teacher_avatar_key in locator.get_attribute('src'):
                print('老师匹配成功')
                locator.click()
                break
        page.get_by_role("button", name="创建(Ctrl+Enter)").click()
        self.page.wait_for_timeout(1000 * 2)

        # 欢迎话语 + @学生
        msg_locator = page.locator('div.lark-editor-wrap')
        msg_locator.locator('pre').type(
            '@',
            delay=0.5)
        self.page.wait_for_timeout(1000 * 1.5)
        at_locator = page.locator('div.lark-mention-box').locator('.larkc-avatar-img')
        for locator in at_locator.all():
            if student_avatar_key in locator.get_attribute('src'):
                locator.click()
                break
        msg_locator.locator('pre').type(' 欢迎加入哈~ 先看下这个指引文档https://yq0pkza686.feishu.cn/docx/SXwOd9BcBoMlVdxeXCDclaKPnfg#OwPKdjWKpol8j9xzNCscCrm7n0d', delay=0.5)
        page.keyboard.press('Shift+Enter')
        page.keyboard.press('Shift+Enter')
        msg_locator.locator('pre').type(
            '学习一下组织文化，会教你如何保持心态不emo+高效学习，总结笔记，',
            delay=0.1)
        page.keyboard.press('Shift+Enter')
        msg_locator.locator('pre').type(
            '之前没加入组织可能会有一些坏习惯和焦虑的心态导致效率不够高。',
            delay=0.1)
        page.keyboard.press('Shift+Enter')
        page.keyboard.press('Shift+Enter')
        msg_locator.locator('pre').type(
            '1 先看视频再看资料 先看八股文再看项目,项目的话 ，你充值，货柜，订单 选择一个去学就可以，作为你的亮点项目~',
            delay=0.1)
        page.keyboard.press('Shift+Enter')
        msg_locator.locator('pre').type(
            '2 如果有不懂的问题，可以随时在大群或者专属群向我们提问',
            delay=0.1)
        page.keyboard.press('Shift+Enter')
        msg_locator.locator('pre').type(
            '3 感觉学完一个阶段了 随时可以找 刘执恒约模拟面试',
            delay=0.1)
        page.keyboard.press('Shift+Enter')
        page.keyboard.press('Shift+Enter')
        msg_locator.locator('pre').type(
            '对你提的要求哈',
            delay=0.1)
        page.keyboard.press('Shift+Enter')
        msg_locator.locator('pre').type(
            '1 八股文路线，看完一定要总结复盘+学习笔记+模拟面试',
            delay=0.1)
        page.keyboard.press('Shift+Enter')
        msg_locator.locator('pre').type(
            '2 一定要找到自己的学习小团体学习搭子，可以直接在群内发消息自我介绍 at所有人',
            delay=0.1)
        page.keyboard.press('Shift+Enter')
        msg_locator.locator('pre').type(
            '也可直接让组长帮你安排合适的小伙伴',
            delay=0.1)
        page.keyboard.press('Shift+Enter')
        page.keyboard.press('Shift+Enter')
        msg_locator.locator('pre').type(
            '还有其他不懂的问题也随时可以在这个群里聊',
            delay=0.1)
        page.keyboard.press('Enter')


        # @老师
        msg_locator.locator('pre').type(
            '@',
            delay=0.1)
        self.page.wait_for_timeout(1000 * 1.5)
        at_locator = page.locator('div.lark-mention-box').locator('.larkc-avatar-img')
        for locator in at_locator.all():
            if teacher_avatar_key in locator.get_attribute('src'):
                locator.click()
                break
        msg_locator.locator('pre').type(
            '这是你的组长，你先看下4月群公告和这个',
            delay=0.1)
        page.keyboard.press('Enter')

        msg_locator.locator('pre').type(
            '然后等组长有空，你们语音聊一下，摸下底，制定学习计划',
            delay=0.1)
        page.keyboard.press('Enter')
        return True

    def close(self):
        self.page.close()
        self.context.close()
        self.browner.close()

    # 判断是否可以建立群组
    def pre_check(self):
        locators = self.page.locator(".lark-drag-disable > .larkc-svg-icon")
        if locators is None:
            print("浏览器未进入指定页面，无法查询到创建群组按钮")
            return False
        return True

    def save_cookies(self):
        """保存Cookies"""
        cookies = self.page.context.cookies()
        with open(self.cookies_file_path, 'w') as f:
            json.dump(cookies, f)

    def load_cookies(self):
        """加载Cookies"""
        with open(self.cookies_file_path, 'r') as f:
            cookies = json.load(f)
            self.context.add_cookies(cookies)


if __name__ == '__main__':
    while True:
        print('\n选择要执行程序的序号：')
        print(' 1. 获取今日学员分组情况创建专属群')
        print(' 2. 退出')
        number = int(input('请输入序号：'))
        if number == 2:
            break
        if number == 1:
            with sync_playwright() as playwright:
                openFeishuMessage = OpenFeishuMessage(playwright)
                openFeishuMessage.open_browser()
                # 对下述方法进行异常捕捉并执行finally
                try:
                    if openFeishuMessage.pre_check():
                        todayStudentData = TodayStudentData()
                        studentData = todayStudentData.getTodayStudentData()
                        callbackMessageList = []
                        if studentData.get('studentAndTeacherDtoList'):
                            for data in studentData.get('studentAndTeacherDtoList'):
                                student = data.get('student')
                                teacher = data.get('teacher')
                                if openFeishuMessage.buildGroup(student, teacher):
                                    status = '成功'
                                else:
                                    status = '失败'
                                    # 重新返回首页
                                    openFeishuMessage.page.goto(openFeishuMessage.lark_suite_url)
                                callbackMessageList.append({'student': student.get('name'), 'teacher': teacher.get('name'), 'status': status})
                        # 发送当日学生导师分配情况
                        callbackData = {'callbackMessageList': callbackMessageList}
                        todayStudentData.sendMsg(callbackData)
                except Exception as e:
                    print('操作异常：%s' % e)
                    openFeishuMessage.close()


